<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span class="text-primary">{{ role.name }}</span>
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button type="primary" @click="setaddress = true">课程包导入</a-button>
          <a-button type="primary" @click="add()">手工添加</a-button>
          <a-button type="primary">
            <router-link class="text-white" :to="{name: '课程'}">返回</router-link>
          </a-button>
        </a-button-group>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-table
          :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
          style="width: 100%; border: 1px solid #eeeeee"
        >
          <el-table-column prop="ID" label="序号" width="60">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="name" label="课程名称"></el-table-column>
          <!-- <el-table-column prop="classhour" sortable label="课时数"></el-table-column> -->
          <!-- <el-table-column prop="paixu" sortable label="排序"></el-table-column> -->
          <el-table-column align="right" width="300px">
            <template slot="header" slot-scope="scope">
              <input
                class="form-control form-control-sm"
                :key="scope.$index"
                v-model.lazy="search"
                placeholder="输入关键字搜索"
              />
            </template>
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="add(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="del(scope.row.ID)">删除</el-button>
              <el-button
                size="mini"
                :disabled="scope.row.ID === classhour[0].ID "
                @click="changes(scope, true)"
                type="info"
              >上移</el-button>
              <el-button
                size="mini"
                :disabled="scope.row.ID === classhour[classhour.length-1].ID "
                @click="changes(scope, false)"
                type="info"
              >下移</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          @current-change="currentChange"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="tableData.length"
        ></el-pagination>
        <el-dialog
          class="school-form"
          title="课程包导入"
          v-loading="loading"
          width="600px"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :show-close="false"
          :visible="setaddress"
        >
          <div class="schoolh container-fluid">
            <div class="row">
              <div class="col over border">
                <div
                  v-for="(v,i) in getpackegekey"
                  @click="packegekeyid = v.ID"
                  :key="`1classhour${i}`"
                  :class="packegekeyid == v.ID?'btn-primary ':'btn-info'"
                  v-text="v.packegeName"
                  class="btn-lg btn-block"
                ></div>
              </div>
              <div class="col over border">
                <el-checkbox-group v-model="checkList">
                  <el-checkbox
                    class="d-block"
                    v-for="(vo,k) in packege"
                    :key="`2classhour${k}`"
                    :label="JSON.stringify({courseid:vo.course.ID, name: vo.course.name})"
                  >{{vo.course.name}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="disabled" size="mini" @click="submitForm">确 定</el-button>
            <el-button @click="setaddress = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog
          class="school-form"
          :show-close="false"
          :title="title"
          width="510px"
          :visible="setaddress2"
        >
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" size="mini">
            <el-form-item label="课程内容：" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <!-- <el-form-item label="课时：" prop="classhour">
              <el-input-number v-model="ruleForm.classhour" :min="1" :max="24"></el-input-number>
            </el-form-item>
            <el-form-item label="排序：">
              <el-input-number v-model="ruleForm.paixu" :min="1"></el-input-number>
            </el-form-item>-->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="disabled" size="mini" @click="submitForm2">确 定</el-button>
            <el-button @click="setaddress2 = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreateschoolclasshour,
  asyncdelschoolclasshour
} from "../../../../plugins/api.js";
export default {
  name: "classhour",
  data() {
    return {
      input: "",
      title: "",
      checkList1: [],
      checkList: [],
      packegekeyid: 0,
      search: "",
      currentPage: 1,
      pagesize: 10,
      setaddress: false,
      setaddress2: false,
      disabled: false,
      loading: false,
      ruleForm: {
        name: "",
        classhour: 1,
        paixu: 1
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        classhour: [{ required: true, message: "请输入课时", trigger: "blur" }]
      }
    };
  },
  props: ["ID"],
  watch: {
    packegekeyid(v) {
      if (v == 0) return;
      this.checkList = this.packege.map(vo =>
        JSON.stringify({ courseid: vo.course.ID, name: vo.course.name })
      );
    }
  },
  computed: {
    ...mapGetters([
      "getpackegekey",
      "getschoolcourse",
      "getschoolclasshour",
      "getschool"
    ]),
    classhour() {
      const { getschoolclasshour } = this;
      return getschoolclasshour.filter(data => {
        if (data.schoolcourseid == this.ID) {
          return true;
        }
      });
    },
    tableData() {
      const { classhour, search } = this;
      return classhour.filter(data => {
        return Object.values(data)
          .join("")
          .toLowerCase()
          .includes(search.toLowerCase());
      });
    },
    role() {
      return this.getschoolcourse.find(v => v.ID == this.ID);
    },
    packege() {
      if (this.packegekeyid) {
        return this.getpackegekey.find(v => v.ID == this.packegekeyid).packege;
      } else {
        return [];
      }
    }
  },
  methods: {
    currentChange(index) {
      this.currentPage = index;
    },
    async changes({ $index }, i) {
      const { currentPage, classhour, pagesize } = this;
      let n;
      const y = classhour[(currentPage - 1) * pagesize + $index];
      if (i) {
        n = classhour[(currentPage - 1) * pagesize + $index - 1];
        if (!n) return;
      } else {
        n = classhour[(currentPage - 1) * pagesize + $index + 1];
        if (!n) return;
      }
      let id = y.ID;
      y.ID = n.ID;
      n.ID = id;
      await asynccreateschoolclasshour(y);
      await asynccreateschoolclasshour(n);
      await this.$store.dispatch("actionschoolclasshour");
    },
    add(v) {
      if (v) {
        this.title = "修改课时";
        const { ID, name, classhour, paixu } = JSON.parse(JSON.stringify(v));
        this.ruleForm = {
          ID,
          name,
          classhour,
          paixu
        };
      } else {
        this.title = "添加课时";
        this.ruleForm = {
          name: "",
          classhour: 1,
          paixu: 1,
          schoolcourseid: this.ID
        };
      }
      this.setaddress2 = true;
    },
    async submitForm() {
      this.disabled = true;
      this.loading = true;
      for (let v of this.checkList) {
        const { courseid, name } = JSON.parse(v);
        await asynccreateschoolclasshour({
          courseid,
          name,
          schoolcourseid: this.ID,
          classhour: 1,
          schoolid: this.getschool.ID
        });
      }
      await this.$store.dispatch("actionschoolclasshour");
      this.checkList = [];
      this.loading = false;
      this.disabled = false;
      this.setaddress = false;
    },
    async submitForm2() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.ruleForm.ID ? "修改" : " 添加";
          try {
            if (data === " 添加") {
              await asynccreateschoolclasshour(this.ruleForm);
            } else {
              await asynccreateschoolclasshour(this.ruleForm);
            }
            await this.$store.dispatch("actionschoolclasshour");
            this.setaddress2 = false;
            this.$message.success(`${data}成功`);
          } catch (err) {
            this.$message.error(`${data}失败:${err}`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    },
    del(ID) {
      this.$confirm("此操作将永久删除该课时, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger"
      })
        .then(async () => {
          try {
            await asyncdelschoolclasshour({ ID });
            await this.$store.dispatch("actionschoolclasshour");
            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
.text-primary {
  display: inline-block;
  padding-right: 15px;
}
.schoolh {
  height: 400px;
  .row {
    height: 100%;
    .over {
      height: 100%;
      overflow-y: scroll;
      padding-left: 0px;
      padding-right: 0px;
      position: relative;
      .btn-lg {
        border-radius: 0;
      }
    }
  }
}
</style>